package com.zcy.util;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class ServiceReciveUtil {
	public static int port = 8821;
	public static DataInputStream inputStream = null;
	public static DataOutputStream outputStream = null;
	public static String savepath = "D:\\";
	public static int length = 0;
	public static int length1=0;
	public static byte[] b;
	public static FileOutputStream fileOutputStream;

	public static void start(Socket socket) {
		//Socket socket = null;
		try {
			//ServerSocket serverSocket = new ServerSocket(port);
				//socket = serverSocket.accept();
				System.out.println("成功建立socket链接");
				// 得到socket输入流,并转化Wiedatainputstream，用于read文件
				inputStream = new DataInputStream(socket.getInputStream());
				// 通过socket输入流read文件
				// 读取文件名，前提是客户端要发送文件名过来
				savepath += inputStream.readUTF();
				// 得到输出流，将收到的文件写入到本地
				//outputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(savepath)));
				
				//写入文件的流
				fileOutputStream = new FileOutputStream(new File(savepath));
				
				long filelength = inputStream.readLong();
				int passedlen = 0;
				b = new byte[8192];
				System.out.println("开始接受文件.....");
				System.out.println("文件大小为:"+filelength);
				
				while(true){
					if(inputStream!=null){
						length = inputStream.read(b, 0, b.length);
						passedlen+=length;
					}
					if (length == -1) {
	                    break;
	                }
					 System.out.println(length);
					 System.out.println("文件接收了" + (passedlen * 100 / filelength) + "%\n");
					 fileOutputStream.write(b, 0, length);
					 fileOutputStream.flush();
				}
				
				/*while ((length = inputStream.read(b, 0,b.length)) > 0) {
					length1 = inputStream.read(b);
					passedlen += length1;
					System.out.println("文件接收了" + (passedlen * 100 / filelength)+ "%\n");
					fileOutputStream.write(b, 0, length);
					fileOutputStream.flush();
				}*/
				System.out.println("接收完成，文件存为" + savepath + "\n");
				// 注意关闭socket链接哦，不然客户端会等待server的数据过来，
				// 直到socket超时，导致数据不完整。
				fileOutputStream.close();
				socket.close();
		
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		//ServiceReciveUtil su = new ServiceReciveUtil();
		//su.start();
		
		Thread thread=new Thread(new Runnable() {
			public void run() {
				ServerSocket serverSocket;
				try {
					serverSocket = new ServerSocket(port);
					while(true){
					System.out.println("端口" + port + "已经开始监听.....");
					Socket socket = serverSocket.accept();
					ServiceReciveUtil.start(socket);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		
		thread.start();
	}
}
